package com.jzo2o.customer.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jzo2o.api.customer.dto.response.AddressBookResDTO;
import com.jzo2o.api.publics.MapApi;
import com.jzo2o.api.publics.dto.response.LocationResDTO;
import com.jzo2o.common.model.PageResult;
import com.jzo2o.common.utils.BeanUtils;
import com.jzo2o.common.utils.CollUtils;
import com.jzo2o.common.utils.NumberUtils;
import com.jzo2o.common.utils.StringUtils;
import com.jzo2o.customer.mapper.AddressBookMapper;
import com.jzo2o.customer.model.domain.AddressBook;
import com.jzo2o.customer.model.dto.request.AddressBookPageQueryReqDTO;
import com.jzo2o.customer.model.dto.request.AddressBookUpsertReqDTO;
import com.jzo2o.customer.service.IAddressBookService;
import com.jzo2o.mvc.utils.UserContext;
import com.jzo2o.mysql.utils.PageUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 地址薄 服务实现类
 * </p>
 *
 * @author itcast
 * @since 2023-07-06
 */
@Service
public class AddressBookServiceImpl extends ServiceImpl<AddressBookMapper, AddressBook> implements IAddressBookService {

    @Resource
    private MapApi mapApi;
    @Resource
    private AddressBookMapper addressBookMapper;

    @Override
    public List<AddressBookResDTO> getByUserIdAndCity(Long userId, String city) {

        List<AddressBook> addressBooks = lambdaQuery()
                .eq(AddressBook::getUserId, userId)
                .eq(AddressBook::getCity, city)
                .list();
        if (CollUtils.isEmpty(addressBooks)) {
            return new ArrayList<>();
        }
        return BeanUtils.copyToList(addressBooks, AddressBookResDTO.class);
    }

    /**
     * 添加地址薄
     *
     * @param reqDTO
     */
    @Override
    @Transactional
    public void addAddressBook(AddressBookUpsertReqDTO reqDTO) {
        //1.先根据传来的地址拼接起来调用地图服务，获取经纬度
        String address = reqDTO.getProvince() + reqDTO.getCity() + reqDTO.getCounty() + reqDTO.getAddress();
        LocationResDTO result = mapApi.getLocationByAddress(address);
        String location = result.getLocation();

        //获取用户id
        Long userId = UserContext.currentUserId();
        //2.判断当前地址是否为默认地址 ,如果是，则将之前默认地址改为非默认
        if (ObjectUtil.equal(reqDTO.getIsDefault(), 1)) {
            super.update(Wrappers.<AddressBook>lambdaUpdate()
                    .eq(AddressBook::getUserId, userId)
                    .set(AddressBook::getIsDefault, 0));
        }

        //3.封装参数
        AddressBook addressBook = BeanUtil.copyProperties(reqDTO, AddressBook.class);
        addressBook.setLon(NumberUtils.parseDouble(location.split(",")[0]));
        addressBook.setLat(NumberUtils.parseDouble(location.split(",")[1]));
        addressBook.setUserId(userId);
        addressBook.setIsDefault(reqDTO.getIsDefault());
        super.save(addressBook);

    }

    /**
     * 获取地址薄列表
     *
     * @param queryReqDTO
     * @return
     */
    @Override
    public PageResult<AddressBook> getAddressBooks(AddressBookPageQueryReqDTO queryReqDTO) {
        Page<AddressBook> page = new Page<>(queryReqDTO.getPageNo(), queryReqDTO.getPageSize());
        LambdaQueryWrapper<AddressBook> wrapper = Wrappers.<AddressBook>lambdaQuery()
                .eq(AddressBook::getUserId, UserContext.currentUserId());

        super.page(page, wrapper);

        return PageUtils.toPage(page, AddressBook.class);
    }

    /**
     * 修改地址薄
     *
     * @param reqDTO
     * @return
     */
    @Override
    @Transactional
    public void updateAddressById(Long id, AddressBookUpsertReqDTO reqDTO) {
        //先删除旧数据
        super.removeById(id);
        //添加新数据
        addAddressBook(reqDTO);
    }

    /**
     * 设置默认地址
     *
     * @param id
     * @param flag
     */
    @Override
    @Transactional
    public void updateDefault(Long id, Integer flag) {
        //将之前默认地址改为非默认
        super.update(Wrappers.<AddressBook>lambdaUpdate()
                .eq(AddressBook::getUserId, UserContext.currentUserId())
                .set(AddressBook::getIsDefault, 0));
        //将当前地址改为默认
        super.update(Wrappers.<AddressBook>lambdaUpdate()
                .eq(AddressBook::getId, id)
                .eq(AddressBook::getUserId, UserContext.currentUserId())
                .set(AddressBook::getIsDefault, flag));

    }

    /**
     * 根据地址id查询地址信息         order 模块主要使用
     *
     * @param addressId
     * @return
     */
    @Override
    public AddressBookResDTO getAddressById(Long addressId) {
        return addressBookMapper.getAddressBookById(addressId);
    }
}
